package com.salt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.salt.entity.IdleAffiliateCpaIncomeDetail;
import com.salt.entity.IdleAffiliateCpsIncomeDetail;
import com.salt.entity.User;
import com.salt.mapper.IdleAffiliateCpaIncomeDetailMapper;
import com.salt.mapper.IdleAffiliateCpsIncomeDetailMapper;
import com.salt.service.IdleAffiliateCpaIncomeDetailService;
import com.salt.service.IdleAffiliateCpsIncomeDetailService;
import com.salt.service.IncomeDetailService;
import com.salt.vo.IncomeDetailVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 收入明细服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class IncomeDetailServiceImpl implements IncomeDetailService {

    private final IdleAffiliateCpaIncomeDetailMapper cpaIncomeDetailMapper;
    private final IdleAffiliateCpsIncomeDetailMapper cpsIncomeDetailMapper;
    private final IdleAffiliateCpsIncomeDetailService cpsIncomeDetailService;
    private final IdleAffiliateCpaIncomeDetailService cpaIncomeDetailService;
    private final UserServiceImpl userService;

    @Override
    public IPage<IncomeDetailVO> pageQuery(Page<IncomeDetailVO> page, String subPublisherId) {
        // 查询CPS收入明细
        Page<IdleAffiliateCpsIncomeDetail> cpsPage = new Page<>(page.getCurrent(), page.getSize());
        LambdaQueryWrapper<IdleAffiliateCpsIncomeDetail> cpsWrapper = new LambdaQueryWrapper<>();
        cpsWrapper.eq(IdleAffiliateCpsIncomeDetail::getSubPublisherId, subPublisherId)
                .in(IdleAffiliateCpsIncomeDetail::getBillState,1,2)
                 .orderByDesc(IdleAffiliateCpsIncomeDetail::getOrderCreateTime);
        IPage<IdleAffiliateCpsIncomeDetail> cpsResult = cpsIncomeDetailMapper.selectPage(cpsPage, cpsWrapper);

        // 查询CPA收入明细
        Page<IdleAffiliateCpaIncomeDetail> cpaPage = new Page<>(page.getCurrent(), page.getSize());
        LambdaQueryWrapper<IdleAffiliateCpaIncomeDetail> cpaWrapper = new LambdaQueryWrapper<>();
        cpaWrapper.eq(IdleAffiliateCpaIncomeDetail::getSubPublisherId, subPublisherId)
                .in(IdleAffiliateCpaIncomeDetail::getState,1,2)
                 .orderByDesc(IdleAffiliateCpaIncomeDetail::getCreateTime);
        IPage<IdleAffiliateCpaIncomeDetail> cpaResult = cpaIncomeDetailMapper.selectPage(cpaPage, cpaWrapper);

        // 合并结果
        List<IncomeDetailVO> voList = new ArrayList<>();
        
        // 转换CPS数据
        for (IdleAffiliateCpsIncomeDetail cps : cpsResult.getRecords()) {
            IncomeDetailVO vo = new IncomeDetailVO();
            vo.setType(1); // CPS类型
            BeanUtils.copyProperties(cps, vo);
            vo.setCreateTime(cps.getOrderCreateTime());
            voList.add(vo);
        }
        
        // 转换CPA数据
       /* for (IdleAffiliateCpaIncomeDetail cpa : cpaResult.getRecords()) {
            IncomeDetailVO vo = new IncomeDetailVO();
            vo.setType(2); // CPA类型
            BeanUtils.copyProperties(cpa, vo);
            voList.add(vo);
        }*/
        
        // 按创建时间排序
        voList.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));
        
        // 计算分页
        int start = (int) ((page.getCurrent() - 1) * page.getSize());
        int end = Math.min(start + (int) page.getSize(), voList.size());
        List<IncomeDetailVO> pageList = voList.subList(start, end);
        
        // 构建分页结果
        Page<IncomeDetailVO> resultPage = new Page<>(page.getCurrent(), page.getSize(), voList.size());
        resultPage.setRecords(pageList);
        
        return resultPage;
    }

    @Override
    public Map<String, Object> getIncomeSummary(Date startDateTime, Date endDateTime, String inviteCode) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> incomeSummaryCps = cpsIncomeDetailService.getIncomeSummary(startDateTime, endDateTime, inviteCode);
        Map<String, Object> incomeSummaryCpa = cpaIncomeDetailService.getIncomeSummary(startDateTime, endDateTime, inviteCode);
        BigDecimal totalAssessAmountCps = toBigDecimal(incomeSummaryCps.get("totalAssessAmount"));
        BigDecimal totalAssessAmountCpa = toBigDecimal(incomeSummaryCpa.get("totalAmount")); // 注意键名是否一致

        // 精确计算总金额
        BigDecimal totalAssessAmount = totalAssessAmountCps.add(totalAssessAmountCpa);
        map.put("totalAssessAmount",totalAssessAmount);
        User inviter = userService.findByInviteCode(inviteCode);
        map.put("totalAmount",inviter.getBalance());
        return map;
    }

    private BigDecimal toBigDecimal(Object value) {
        if (value == null) {
            return BigDecimal.ZERO;
        }
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }
        if (value instanceof String) {
            try {
                return new BigDecimal((String) value);
            } catch (NumberFormatException e) {
                // 记录日志或抛出自定义异常
                return BigDecimal.ZERO;
            }
        }
        if (value instanceof Number) {
            return new BigDecimal(value.toString());
        }
        // 未知类型，记录异常并返回 0
        return BigDecimal.ZERO;
    }
} 